package com.demo.autoconfigure;

import com.demo.filter.SignFilter;
import com.demo.interceptor.SignInterceptor;
import com.demo.properties.SignInterceptorProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Description 签名拦截器自动装配类
 * @Author Dang Xianyue
 * @Date 2020-08-09 13:33
 * @Version 1.0
 */
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass(SignInterceptor.class)
@EnableConfigurationProperties(SignInterceptorProperties.class)
@ConditionalOnProperty(prefix = "com.demo.sign.interceptor",value = "enabled",havingValue = "true")
public class SignInterceptorAutoConfigure implements WebMvcConfigurer {

    @Autowired
    private SignInterceptorProperties signInterceptorProperties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SignInterceptor(signInterceptorProperties))
                .addPathPatterns(signInterceptorProperties.getIncludePaths())
                .excludePathPatterns(signInterceptorProperties.getExcludePaths());
    }

    @Bean
    public FilterRegistrationBean newFilterRegistrationBean1() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new SignFilter());
        bean.setName("SignFilter");
        String[] strArr = signInterceptorProperties.getIncludePaths();
        for (int i = 0; i < strArr.length; i++) {
            strArr[i] = strArr[i].replace("**","*");
        }
        bean.addUrlPatterns(strArr);
        return bean;
    }
}
